//
//  IGCommunitySearchVC.m
//  jingdongfang
//
//  Created by BOE on 2017/8/24.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGCommunitySearchVC.h"
#import "FTPopOverMenu.h"
#import "IGSearchBar.h"
#import "IGCommunityDetailVC.h"
#import "IGCommunityListTableViewCell.h"
#import "IGTopicDetailVC.h"
#import "IGEmptyView.h"

@interface IGCommunitySearchVC ()<UISearchBarDelegate>

@property (nonatomic, strong) IGSearchBar *searchBar;
@property (nonatomic, strong) IGMainSearchApi *searchApi;
@property (nonatomic, assign) NSInteger tpage;
@property (nonatomic, assign) NSInteger cpage;
@property (nonatomic, copy) NSString *searchKey;
@property (nonatomic, strong) NSMutableArray *circleMuArr;

@end

@implementation IGCommunitySearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.heightForFirstSectionCell = 0.0f;
    
    self.tpage = 0;
    self.cpage = 0;
    self.searchType = IGSearchTypeTopic;
    self.searchApi = [IGMainSearchApi new];
    self.requestApi = self.searchApi;
    
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    
    [self initNavbar];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setHeaderWithRefreshingBlock:^{
        if (weakSelf.searchType == IGSearchTypeCircle) {
            weakSelf.cpage = 0;
        } else {
            weakSelf.tpage = 0;
        }
        [weakSelf requestData];
    }];
}

- (void)initNavbar {
    UIView *leftBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 5, 44)];
    UIBarButtonItem *leftBtnItem = [[UIBarButtonItem alloc]initWithCustomView:leftBarView];
    UIBarButtonItem *leftSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    leftSpaceItem.width = -15;
    self.navigationItem.leftBarButtonItems = @[leftSpaceItem, leftBtnItem];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Cancel", nil) image:nil highLightedImage:nil];
    if (@available(iOS 11, *)) {
        UIView *searchbg = [[UIView alloc]init];
        searchbg.backgroundColor = [UIColor clearColor];
        self.navigationItem.titleView = searchbg;
        [searchbg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(KSCREENWIDTH - 90);
        }];
        [searchbg addSubview:self.searchBar];
        [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(searchbg).with.offset(7.0);
            make.left.equalTo(searchbg).with.offset(0);
            make.right.equalTo(searchbg).with.offset(-10);
            make.bottom.equalTo(searchbg).with.offset(-7.0);
        }];
        self.navigationItem.titleView = searchbg;
    } else {
        [self.searchBar setFrame:CGRectMake(0, 0, KSCREENWIDTH, 44)];
        self.navigationItem.titleView = self.searchBar;
    }
}

- (void)ig_rightButtonPressed:(id)sender {
    [self.searchBar resignFirstResponder];
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.searchBar endEditing:YES];
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        __weak typeof(self) weakSelf = self;
        _searchBar = [IGSearchBar searchBarSearchIconBlock:^(UIView *view) {
            NSArray *menuArray = @[NSLocalizedString(@"Search Topic", nil),NSLocalizedString(@"Search Group", nil)];
            [FTPopOverMenu showForSender:view
                           withMenuArray:menuArray
                               doneBlock:^(NSInteger selectedIndex) {
                                   if (selectedIndex == 0) {
                                       weakSelf.searchType = IGSearchTypeTopic;
                                       weakSelf.searchBar.placeholder = NSLocalizedString(@"Search Topic", nil);
                                       if (weakSelf.dataSource.count > 0) {
                                           [weakSelf.tableView reloadData];
                                           [weakSelf setupFooter];
                                       } else {
                                           [weakSelf requestData];
                                       }
                                   } else if (selectedIndex == 1) {
                                       weakSelf.searchType = IGSearchTypeCircle;
                                       weakSelf.searchBar.placeholder = NSLocalizedString(@"Search Group", nil);
                                       if (weakSelf.circleMuArr.count > 0) {
                                           [weakSelf.tableView reloadData];
                                           [weakSelf setupFooter];
                                       } else {
                                           [weakSelf requestData];
                                       }
                                   }
                               } dismissBlock:^{
                               }];
        }];
        _searchBar.showsCancelButton = NO;
        _searchBar.delegate = self;
        _searchBar.placeholder = NSLocalizedString(@"Search Topic", nil);

    }
    return _searchBar;
}

- (void)setupFooter {
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        if (weakSelf.searchType == IGSearchTypeCircle) {
            weakSelf.cpage++;
        } else {
            weakSelf.tpage++;
        }
        [weakSelf requestData];
    }];
}

- (void)requestData {
    if (!self.searchKey || [self.searchKey isEqualToString:@""]) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    self.searchApi.searchKey = self.searchKey;
    if (weakSelf.searchType == IGSearchTypeCircle) {
        self.searchApi.page = weakSelf.cpage;
    } else {
        self.searchApi.page = weakSelf.tpage;
    }
    self.searchApi.type = self.searchType;
    [self.searchApi startWithDecodeClass:[IGMainSearchResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        if (responseObject) {
            IGMainSearchResp *resp = responseObject;
            IGMainSearchModel *model = resp.data;
            
            if (weakSelf.searchType == IGSearchTypeTopic) {
                NSArray *tmpArr = model.lstTopic;
                if (tmpArr && tmpArr.count > 0) {
                    [weakSelf setupFooter];
                } else {
                    [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
                }
               
                if (weakSelf.tpage == 0) {
                    weakSelf.dataSource = [NSMutableArray arrayWithArray:tmpArr];
                } else {
                    [weakSelf.dataSource addObjectsFromArray:tmpArr];
                }
                
            } else {
                NSArray *tmpArr = model.lstCircle;
                if (tmpArr && tmpArr.count > 0) {
                    [weakSelf setupFooter];
                } else {
                    [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
                }
                if (weakSelf.cpage == 0) {
                    weakSelf.circleMuArr = [NSMutableArray arrayWithArray:tmpArr];
                } else {
                    [weakSelf.circleMuArr addObjectsFromArray:tmpArr];
                }
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    }];
}

#pragma mark - <>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchType == IGSearchTypeCircle) {
        if (section == 0) {
            return 1;
        } else {
            return self.circleMuArr.count;
        }
    }
    return [super tableView:tableView numberOfRowsInSection:section];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchType == IGSearchTypeCircle) {
        return self.circleMuArr.count>0?2:0;
    }
    return [super numberOfSectionsInTableView:tableView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchType == IGSearchTypeCircle) {
        if (indexPath.section == 0) {
            return self.heightForFirstSectionCell;
        } else {
            return 90;
        }
    }
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchType == IGSearchTypeCircle) {
        if (indexPath.section == 0) {
            return [super customFirstSectionCell:tableView];
        } else if (indexPath.section == 1) {
            IGCommunityListTableViewCell *cell = [IGCommunityListTableViewCell cellWithTableView:tableView listType:IGCommunityListTypeAll];
            
            IGCommunityModel *model = self.circleMuArr[indexPath.row];
            
            cell.itemModel = model;
            
            return cell;
        }
    }
    return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.isShowKeyBoard) {
        [self.view endEditing:YES];
        return;
    }
    
    if (self.searchType == IGSearchTypeCircle) {
        IGCommunityModel *model = self.circleMuArr[indexPath.row];
//        IGCommunityDetailVC *detailVC = [[IGCommunityDetailVC alloc] initWithCid:model.cid];
        IGCommunityDetailVC *detailVC = [[IGCommunityDetailVC alloc] initWithCid:model.cid type:GROUP_TITLE_GROUP_DETAILS];
        [UIViewController ig_pushViewController:detailVC animated:YES];
        return;
    } else {
        IGTopicModel *model = self.dataSource[indexPath.row];
        IGTopicDetailVC *detailVC = [[IGTopicDetailVC alloc] initWithTopicId:model.tid];
        [UIViewController ig_pushViewController:detailVC animated:YES];
    }
}

#pragma mark - <UISearchBarDelegate>
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    
    self.searchKey = searchBar.text;
    if (self.searchType == IGSearchTypeCircle) {
        self.cpage = 0;
    } else {
        self.tpage = 0;
    }
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
